package com.kwer.example.springbootwebsocketdemo.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

/**
 * websocket 服务
 * 可以丢这里测试 websocket   http://coolaf.com/tool/chattest
 *
 * @author kwer
 * @date 2019/8/17 19:18
 */
@Component
@ServerEndpoint("/ws")
public class WebsocketService {
    private Logger log = LoggerFactory.getLogger(this.getClass());

    /**
     * 建立连接调用的方法
     *
     * @param session Session
     */
    @OnOpen
    public void onOpen(Session session) {
        log.info("关闭连接");
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        log.info("关闭连接");
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param msg 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String msg, Session session) {
        log.info("收到消息:[{}]", msg);
        try {
            session.getBasicRemote().sendText("收到消息:" + msg);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 连接错误
     *
     * @param session Session
     * @param e       Throwable
     */
    @OnError
    public void onError(Session session, Throwable e) {
        log.error("websocket IO异常", e);
    }
}
